﻿/*** MikeWare Framework ************************************
* This class is part of product of MikeWare.Framework.
* 
* Author      : Mike Cheers
* Mail        : mikecheers@126.com
* Create Date : 2018/9/14
* Summary     : 
* 
* 
* Modified By : 
* Date        : 
* Mail        : 
* Comment     : 
**************************************************************/

namespace MikeWare.Core.Extensions
{
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Text;

    public static class ExceptionEx
    {
        public static string GetExceptionContent(this Exception ex)
        {
            return ex.GetExceptionContent(ex.Message);
        }
        public static string GetExceptionContent(this Exception ex, string message)
        {
            var win32code = Marshal.GetLastWin32Error();

            if (null == ex) return (message ?? "<null>") + "; LastWin32ErrorCode:" + win32code + ";";

            StackTrace st = new StackTrace(ex, true);

            StringBuilder builder = new StringBuilder(Environment.NewLine + ((message ?? "<null>") + "; LastWin32ErrorCode:" + win32code + ";"));

            if (!string.IsNullOrEmpty(ex.Message))
                builder.Append(Environment.NewLine + ex.Message);

            if (null != st.GetFrames())
            {
                builder.Append(Environment.NewLine + "- - - - - - - - - - - - - - - -");
                foreach (var frm in st.GetFrames())
                {
                    if (frm != null && null != frm.GetFileName())
                    {
                        builder.Append(Environment.NewLine
                            + frm.GetFileName()
                            + "(" + frm.GetFileLineNumber()
                            + "," + frm.GetFileColumnNumber() + ")");
                    }
                }
            }

            if (null != ex.InnerException)
            {
                builder.Append(ex.InnerException.GetExceptionContent());
            }

            return builder.ToString();
        }
    }
}
